// @/utils/iatService.js
import CryptoJS from 'crypto-js';

export default class IatService {
  constructor(appId, apiKey, apiSecret) {
    this.APPID = appId;
    this.API_KEY = apiKey;
    this.API_SECRET = apiSecret;

    this.status = "UNDEFINED"; // "UNDEFINED" "CONNECTING" "OPEN" "CLOSING" "CLOSED"
    this.iatWS = null;
    this.resultText = "";
    this.resultTextTemp = "";
    this.countdownInterval = null;
    this.onResultChange = null;
    this.onStatusChange = null;
    this.onWsStatusChange = null;

    // 新增：音频数据缓冲区
    this.audioBufferQueue = [];
    this.isProcessing = false;
    this.audioSendInterval = null;
  }

  // 获取websocket url
  _getWebSocketUrl() {
    const url = "wss://iat-api.xfyun.cn/v2/iat";
    const host = "iat-api.xfyun.cn";
    const apiKey = this.API_KEY;
    const apiSecret = this.API_SECRET;
    const date = new Date().toGMTString();
    const algorithm = "hmac-sha256";
    const headers = "host date request-line";
    const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat HTTP/1.1`;
    const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    const signature = CryptoJS.enc.Base64.stringify(signatureSha);
    const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    const authorization = btoa(authorizationOrigin);
    return `${url}?authorization=${authorization}&date=${encodeURIComponent(date)}&host=${host}`;
  }

  _toBase64(buffer) {
    let binary = "";
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  }

  _countdown() {
    let seconds = 60;
    this._updateStatus(`录音中（${seconds}s）`);

    this.countdownInterval = setInterval(() => {
      seconds = seconds - 1;
      if (seconds <= 0) {
        clearInterval(this.countdownInterval);
        this.stopRecording();
      } else {
        this._updateStatus(`录音中（${seconds}s）`);
      }
    }, 1000);
  }

  _changeStatus(status) {
    this.status = status;
    if (status === "CONNECTING") {
      this._updateStatus("建立连接中");
      this._updateResult("");
      this.resultText = "";
      this.resultTextTemp = "";
    } else if (status === "OPEN") {
      this._countdown();
    } else if (status === "CLOSING") {
      this._updateStatus("关闭连接中");
    } else if (status === "CLOSED") {
      this._updateStatus("准备就绪");
    }
  }

  // 在IatService.js中修改_renderResult方法
  _renderResult(resultData) {
    try {
      console.log('📨 收到WebSocket消息:', resultData);

      const jsonData = JSON.parse(resultData);
      console.log('📋 解析后的JSON:', jsonData);

      if (jsonData.code !== 0) {
        console.error('❌ 讯飞语音识别错误:', jsonData);
        this.iatWS.close();
        return;
      }

      if (jsonData.data && jsonData.data.result) {
        const data = jsonData.data.result;
        console.log('🎯 识别结果数据:', data);

        let str = "";
        const ws = data.ws;
        for (let i = 0; i < ws.length; i++) {
          if (ws[i].cw && ws[i].cw.length > 0) {
            str += ws[i].cw[0].w;
          }
        }

        console.log('🔤 提取的文本:', str);

        if (data.pgs === "apd") {
          this.resultText = this.resultTextTemp;
          this.resultTextTemp = this.resultText + str;
        } else if (data.pgs === "rpl") {
          this.resultTextTemp = this.resultText + str;
        } else {
          this.resultText = this.resultText + str;
          this.resultTextTemp = this.resultText;
        }

        console.log('📝 最终结果:', this.resultTextTemp || this.resultText);
        this._updateResult(this.resultTextTemp || this.resultText || "");
      }

      if (jsonData.code === 0 && jsonData.data.status === 2) {
        console.log('✅ 识别完成，关闭连接');
        this.iatWS.close();
      }

    } catch (error) {
      console.error('❌ 解析识别结果失败:', error, '原始数据:', resultData);
    }
  }

  // 关键修复：增强WebSocket连接方法
  _connectWebSocket() {
    const websocketUrl = this._getWebSocketUrl();

    if ("WebSocket" in window) {
      this.iatWS = new WebSocket(websocketUrl);
    } else if ("MozWebSocket" in window) {
      this.iatWS = new MozWebSocket(websocketUrl);
    } else {
      this._updateStatus("浏览器不支持WebSocket");
      this._updateWsStatus("disconnected", "浏览器不支持WebSocket");
      return false;
    }

    this._changeStatus("CONNECTING");
    this._updateWsStatus("connecting", "连接中...");

    this.iatWS.onopen = (e) => {
      console.info('WebSocket连接成功', e);
      this._changeStatus("OPEN");
      this._updateWsStatus("connected", "已连接");

      const params = {
        common: {
          app_id: this.APPID,
        },
        business: {
          language: "zh_cn",
          domain: "iat",
          accent: "mandarin",
          vad_eos: 5000,
          dwa: "wpgs",
        },
        data: {
          status: 0,
          format: "audio/L16;rate=16000",
          encoding: "raw",
        },
      };

      this.iatWS.send(JSON.stringify(params));

      // 开始处理音频数据队列
      this._startAudioProcessing();
    };

    this.iatWS.onmessage = (e) => {
      this._renderResult(e.data);
    };

    this.iatWS.onerror = (e) => {
      console.error('WebSocket错误:', e);
      this._updateStatus("连接错误");
      this._updateWsStatus("error", "连接错误");
      this._changeStatus("CLOSED");
      this._stopAudioProcessing();
    };

    this.iatWS.onclose = (e) => {
      console.info('WebSocket连接关闭', e);
      this._changeStatus("CLOSED");
      this._updateWsStatus("disconnected", "已断开");
      this._stopAudioProcessing();
    };

    return true;
  }

  // 新增：开始处理音频数据
  _startAudioProcessing() {
    // 清空之前的缓冲区
    this.audioBufferQueue = [];
    this.isProcessing = true;

    // 设置定时器处理音频队列
    this.audioSendInterval = setInterval(() => {
      this._processAudioBufferQueue();
    }, 100); // 每100ms处理一次
  }

  // 新增：停止处理音频数据
  _stopAudioProcessing() {
    this.isProcessing = false;
    if (this.audioSendInterval) {
      clearInterval(this.audioSendInterval);
      this.audioSendInterval = null;
    }
    this.audioBufferQueue = [];
  }

  // 新增：处理音频数据队列
  _processAudioBufferQueue() {
    if (!this.isProcessing || !this.iatWS || this.iatWS.readyState !== WebSocket.OPEN) {
      return;
    }

    // 处理队列中的所有音频数据
    while (this.audioBufferQueue.length > 0) {
      const audioData = this.audioBufferQueue.shift();
      this._sendAudioData(audioData);
    }
  }

  // 新增：内部发送音频数据方法
  // 在IatService.js中修改_sendAudioData方法
  _sendAudioData(audioBuffer) {
    try {
      if (!this.iatWS || this.iatWS.readyState !== WebSocket.OPEN) {
        console.warn('WebSocket未连接，无法发送音频数据');
        return false;
      }

      // 确保是ArrayBuffer或类似格式
      let bufferToSend;
      if (audioBuffer instanceof Float32Array) {
        // Float32Array转换为Int16Array
        bufferToSend = new Int16Array(audioBuffer.length);
        for (let i = 0; i < audioBuffer.length; i++) {
          bufferToSend[i] = Math.max(-32768, Math.min(32767, audioBuffer[i] * 32768));
        }
      } else if (audioBuffer instanceof ArrayBuffer) {
        bufferToSend = audioBuffer;
      } else if (audioBuffer.buffer instanceof ArrayBuffer) {
        bufferToSend = audioBuffer.buffer;
      } else {
        console.error('不支持的音频格式:', audioBuffer);
        return false;
      }

      // 转换为base64
      const base64Audio = this._toBase64(bufferToSend);

      if (!base64Audio || base64Audio.length === 0) {
        console.error('Base64编码失败');
        return false;
      }

      const audioData = {
        data: {
          status: 1,
          format: "audio/L16;rate=16000",
          encoding: "raw",
          audio: base64Audio,
        },
      };

      console.log(`📤 发送音频数据: ${base64Audio.length} bytes`);
      this.iatWS.send(JSON.stringify(audioData));
      return true;
    } catch (error) {
      console.error('发送音频数据失败:', error);
      return false;
    }
  }

  _updateStatus(status) {
    if (this.onStatusChange && typeof this.onStatusChange === 'function') {
      this.onStatusChange(status);
    }
  }

  _updateResult(result) {
    if (this.onResultChange && typeof this.onResultChange === 'function') {
      this.onResultChange(result);
    }
  }

  // 新增：更新WebSocket状态
  _updateWsStatus(status, text) {
    if (this.onWsStatusChange && typeof this.onWsStatusChange === 'function') {
      this.onWsStatusChange(status, text);
    }
  }

  // 开始录音
  startRecording() {
    if (this.status === "UNDEFINED" || this.status === "CLOSED") {
      // 清空音频缓冲区
      this.audioBufferQueue = [];
      return this._connectWebSocket();
    }
    return false;
  }

  // 停止录音
  stopRecording() {
    if (this.status === "CONNECTING" || this.status === "OPEN") {
      if (this.iatWS && this.iatWS.readyState === WebSocket.OPEN) {
        // 发送结束帧
        this.iatWS.send(
          JSON.stringify({
            data: {
              status: 2,
              format: "audio/L16;rate=16000",
              encoding: "raw",
              audio: "",
            },
          })
        );
      }
      this._changeStatus("CLOSING");
    }

    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }

    // 停止音频处理
    this._stopAudioProcessing();
  }

  // 发送音频数据 - 公开方法
  sendAudioData(audioBuffer) {
    if (this.isProcessing && this.iatWS && this.iatWS.readyState === WebSocket.OPEN) {
      // 将音频数据添加到队列
      this.audioBufferQueue.push(audioBuffer);
      return true;
    }
    return false;
  }

  // 设置回调函数
  setCallbacks(onResultChange, onStatusChange, onWsStatusChange = null) {
    this.onResultChange = onResultChange;
    this.onStatusChange = onStatusChange;
    this.onWsStatusChange = onWsStatusChange;
  }

  // 新增：销毁方法
  destroy() {
    this.stopRecording();
    if (this.iatWS) {
      this.iatWS.close();
    }
    this._stopAudioProcessing();
    this.audioBufferQueue = [];
  }
}